import { init } from 'snabbdom/build/package/init'
import { h } from 'snabbdom/build/package/h'
import { styleModule } from 'snabbdom/build/package/modules/style'
import { eventListenersModule } from 'snabbdom/build/package/modules/eventlisteners'

let data = [
  {
    rank: 1,
    title: "title-1",
    desc: "路遥知马力日久见人心。",
    score: 9.7,
  },
  {
    rank: 2,
    title: "title-2",
    desc: "红时不追，难时不黑；只赏其作，不问是非。",
    score: 9.6,
  },
  {
    rank: 3,
    title: "title-3",
    desc: "往事如烟卿莫问，三生树下忆平生。我是人间惆怅客，知君何事泪纵横。",
    score: 9.2,
  },
  {
    rank: 4,
    title: "title-4",
    desc: "静坐常思己过，闲谈莫论人非。",
    score: 9.4,
  },
  {
    rank: 5,
    title: "title-5",
    desc: "未曾清贫难成人，不经打击老天真。自古英雄出炼狱，从来富贵入凡尘。",
    score: 9.3,
  },
  {
    rank: 6,
    title: "title-6",
    desc: "世间难熬，连神明都在劫难逃。",
    score: 9.3,
  },
]

const patch = init([
  styleModule,
  eventListenersModule
])

let vnode = null;

function dataView(data) {
  return h('div.row', {
    key: data.rank,
    style: {
      opacity: 0,
      transform: 'translate(-200px)',
      delayed: { transform: `translateY(${data.offset}px)`, opacity: '1' },
      remove: { opacity: '0', transform: `translateY(${data.offset}px) translateX(200px)` }
    }
  }, [
    h('div', { style: { fontWeight: 'bold' } }, data.rank),
    h('div', data.title),
    h('div', data.desc),
    h('div', data.score),
    h('div.rm-btn', { on: { click: () => { remove(data) } } }, 'x'),
  ])
}

function view(data) {
  return h('div', [
    h('h1', '人生八九不如意'),
    h('div', [
      h('span', '按以下排序： '),
      h('button', {
        on: {
          click: () => { sortType('rank') }
        }
      }, 'Rank'),
      h('button', {
        on: {
          click: () => { sortType('score') }
        }
      }, 'Score'),
      h('di.add', [
        h('button', {
          on: {
            click: addData
          }
        }, '新增')
      ]),
    ]),
    h('div', data.map(dataView))
  ])
}

// 渲染
function render() {
  data.forEach((item, index) => {
    item.offset = index * 80
  })
  let newvnode = h('div.list', {}, view(data))
  vnode = patch(vnode, newvnode)
}

function sortType(type) {
  data.sort((a, b) => {
    if (a[type] > b[type]) {
      return 1
    }
    if (a[type] < b[type]) {
      return -1
    }
    return 0
  })
  render()
}

// 新增
function addData() {
  data.push({
    rank: data.length,
    title: "title-" + data.length,
    desc: "世间苦难并非不能忍受，给钱就行。",
    score: 9.8
  })
  render()
}

// 删除
function remove(obj) {
  let temp = []
  data.forEach(item => {
    if (obj.title !== item.title) {
      temp.push(item)
    }
  })
  data = temp
  render()
}

let app = document.querySelector("#app")
vnode = patch(app, view(data))
render()